<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1280">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              filterable
              clearable
              v-model="formData.customerId"
              placeholder="请选择客户"
              class="w-1/1"
              @change="handleCustomerChange"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入订单名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单编号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下单人" prop="ownerUserId">
            <el-select
              v-model="formData.ownerUserId"
              :disabled="true"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="税率" prop="taxRate">
            <el-input v-model="formData.taxRate" placeholder="请输入税率" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺名称" prop="storeName">
            <el-input v-model="formData.storeName" placeholder="请输入店铺名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺面积" prop="storeArea">
            <el-input v-model="formData.storeArea" placeholder="请输入店铺面积" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务员" prop="signUserId">
            <el-select v-model="formData.signUserId" class="w-1/1">
              <el-option
                filterable
                clearable
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户订单编号" prop="customerOrderNo">
            <el-input v-model="formData.customerOrderNo" placeholder="请输入客户订单编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手工订单编号" prop="manualOrderNo">
            <el-input v-model="formData.manualOrderNo" placeholder="请输入手工订单编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售范围" prop="salesScope">
            <el-input v-model="formData.salesScope" placeholder="请输入销售范围" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售代理商" prop="salesAgent">
            <el-input v-model="formData.salesAgent" placeholder="请输入销售代理商" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单类型" prop="orderType">
            <el-select
              filterable
              clearable
              v-model="formData.orderType"
              placeholder="请选择订单类型"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select
              filterable
              clearable
              v-model="formData.orderStatus"
              placeholder="请选择订单状态"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="约定发货时间" prop="shipTime">
            <el-date-picker
              v-model="formData.shipTime"
              type="date"
              value-format="x"
              placeholder="选择发货时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="约定到货时间" prop="deliveryTime">
            <el-date-picker
              v-model="formData.deliveryTime"
              type="date"
              value-format="x"
              placeholder="选择到货时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交货方式" prop="deliveryType">
            <el-select
              filterable
              clearable
              v-model="formData.deliveryType"
              placeholder="请选择交货方式"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货联系人" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入收货联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人电话" prop="signContactPhone">
            <el-input v-model="formData.signContactPhone" placeholder="请输入联系人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发货单号" prop="slipNo">
            <el-input disabled v-model="formData.slipNo" placeholder="发货时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货地区" prop="areaId">
            <el-cascader
              clearable
              filterable
              v-model="formData.areaId"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              placeholder="请选择收货地区"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货详细地址" prop="detailAddress">
            <el-input v-model="formData.detailAddress" placeholder="请输入收货详细地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <ContentWrap v-show="showSubForm">
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px" >
          <el-tab-pane label="产品清单" name="product">
            <ContractProductForm ref="productFormRef" :products="formData.products"
                                 :customerId="formData.customerId"
                                 :disabled="disabled"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-row  v-show="false">
        <el-col :span="8">
          <el-form-item label="产品总金额" prop="totalProductPrice">
            <el-input
              disabled
              v-model="formData.totalProductPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="false">
          <el-form-item label="整单折扣（%）" prop="discountPercent">
            <el-input-number
              v-model="formData.discountPercent"
              placeholder="请输入整单折扣"
              controls-position="right"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8"  v-show="false">
          <el-form-item label="折扣后金额" prop="totalPrice">
            <el-input
              disabled
              v-model="formData.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">保存</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as CustomerApi from '@/api/crm/customer'
import * as ContractApi from '@/api/crm/contract'
import * as UserApi from '@/api/system/user'
import * as ContactApi from '@/api/crm/contact'
import * as BusinessApi from '@/api/crm/business'
import { erpPriceMultiply, erpPriceInputFormatter } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import ContractProductForm from '@/views/crm/contract/components/ContractProductForm.vue'
import {StoreApi} from "@/api/crm/store";
import * as AreaApi from "@/api/system/area";
import {BrandApi} from "@/api/crm/brand";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const showSubForm = ref(true) // 展示子表单
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  name: undefined,
  customerId: undefined,
  businessId: undefined,
  orderDate: undefined,
  startTime: undefined,
  endTime: undefined,
  signUserId: undefined,
  signContactId: undefined,
  ownerUserId: undefined,
  discountPercent: 0,
  totalProductPrice: undefined,
  remark: undefined,
  products: [],
  storeId: undefined,
  storeName: undefined,
  storeArea: undefined,
  slipNo: undefined,
  orderType: undefined,
  orderStatus: undefined,
  deliveryType: undefined,
  shipTime: undefined,
  deliveryTime: undefined,
  signContactPhone: undefined,
  areaId: undefined,
  detailAddress: undefined,
  salesScope: undefined,
  salesAgent: undefined,
  customerOrderNo: undefined,
  manualOrderNo: undefined,
  taxRate: 13,
})
const formRules = reactive({
  name: [{ required: true, message: '订单名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  // orderDate: [{ required: true, message: '下单日期不能为空', trigger: 'blur' }],
  ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
  // auditStatus: [{ required: true, message: '审批状态不能为空', trigger: 'blur' }],
  // discountPercent: [{ required: true, message: '整单折扣率不能为空', trigger: 'blur' }],
  orderStatus: [{ required: true, message: '订单状态不能为空', trigger: 'blur' }],
  orderType: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'change' }],
  signContactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'change' }],
  areaId: [{ required: true, message: '收货地区不能为空', trigger: 'change' }],
  detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const businessList = ref<BusinessApi.BusinessVO[]>([])
const contactList = ref<ContactApi.ContactVO[]>([])
const customerList = ref([]) // 客户列表的数据
const storeList = ref([]) // 门店列表的数据
const brandList = ref([]) // 品牌列表的数据
const areaList = ref([]) // 地区列表


/** 子表的表单 */
const subTabsName = ref('product')
const productFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    const totalProductPrice = val.products.reduce((prev, curr) => prev + curr.totalPrice, 0)
    const discountPrice =
      val.discountPercent != null
        ? erpPriceMultiply(totalProductPrice, val.discountPercent / 100.0)
        : 0
    const totalPrice = totalProductPrice - discountPrice
    // 赋值
    formData.value.totalProductPrice = totalProductPrice
    formData.value.totalPrice = totalPrice
  },
  { deep: true }
)
/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    showSubForm.value = false
    formLoading.value = true
    try {
      formData.value = await ContractApi.getContract(id)
      formData.value.products = []
    } finally {
      formLoading.value = false
    }
  }
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
    formData.value.orderStatus = '10'
    formData.value.deliveryType = '1'
    formData.value.orderType = '01'
  }
  // 获取联系人
  contactList.value = await ContactApi.getSimpleContactList()
  // 获得商机列表
  // businessList.value = await BusinessApi.getSimpleBusinessList()
  storeList.value = await StoreApi.getStoreSimpleList()
  brandList.value = await BrandApi.getBrandSimpleList()
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()

  if (customerId) {
    formData.value.customerId = customerId
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  productFormRef.value.validate()
  try {
    const data = unref(formData.value) as unknown as ContractApi.ContractVO
    if (formType.value === 'create') {
      await ContractApi.createContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractApi.updateContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    name: undefined,
    customerId: undefined,
    businessId: undefined,
    orderDate: undefined,
    startTime: undefined,
    endTime: undefined,
    signUserId: undefined,
    signContactId: undefined,
    ownerUserId: undefined,
    discountPercent: 0,
    totalProductPrice: undefined,
    remark: undefined,
    customerOrderNo: undefined,
    manualOrderNo: undefined,
    taxRate: 13,
    products: []
  }
  formRef.value?.resetFields()
}

/** 处理切换客户 */
const handleCustomerChange = () => {
  // formData.value.businessId = undefined
  // formData.value.signContactId = undefined
  // formData.value.products = []
}

/** 处理商机变化 */
const handleBusinessChange = async (businessId: number) => {
  const business = await BusinessApi.getBusiness(businessId)
  business.products.forEach((item) => {
    item.contractPrice = item.businessPrice
  })
  formData.value.products = business.products
}

/** 动态获取客户联系人 */
const getContactOptions = computed(() =>
  contactList.value.filter((item) => item.customerId == formData.value.customerId)
)
/** 动态获取商机 */
// const getBusinessOptions = computed(() =>
//   businessList.value.filter((item) => item.customerId == formData.value.customerId)
// )

/** 动态获取门店 */
const getStoreOptions = computed(() =>
  storeList.value.filter((item) => item.customerId == formData.value.customerId)
)
const getBrandOptions = computed(() =>
  brandList.value.filter((item) => item.customerId == formData.value.customerId)
)
/*店铺变更*/
const onChangeStore = (event) => {
  const selectedOptionObj = storeList.value.find(opt => opt.id === event); // 找到对应的对象
  formData.value.areaId = selectedOptionObj.areaId
  formData.value.detailAddress = selectedOptionObj.detailAddress
  // formRef.value?.resetFields()
}
// const onChangeBrand = (event) => {
//   const selectedOptionObj = brandList.value.find(opt => opt.id === event); // 找到对应的对象
//   formData.value.areaId = selectedOptionObj.areaId
//   formData.value.detailAddress = selectedOptionObj.detailAddress
//   // formRef.value?.resetFields()
// }
const onChangeContact = (event) => {
  const selectedOptionObj = contactList.value.find(opt => opt.id === event); // 找到对应的对象
  formData.value.signContactPhone = selectedOptionObj.mobile
}
</script>
